package com.yanzhu.api;

import com.yanzhu.bean.ResponseBean;
import com.yanzhu.constant.Constant;
import com.yanzhu.service.*;
import com.yanzhu.service.model.*;
import com.yanzhu.util.RandomUtils;
import lombok.AllArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * @Author: 方炎柱
 * @Description:
 * @Date: Created in 15:55 2018/1/29
 * @Modified:
 */
@AllArgsConstructor
@RestController
@Log4j2
public class RedPacketsApi {
    private final RedPacketsService redPacketsService;

    private final GrabRedPacketsService grabRedPacketsService;

    private final WalletService walletService;

    private VideoService videoService;

    private UserService userService;

    private final RedisTemplate<Object, Object> redisTemplate;

    private static Logger logger = LoggerFactory.getLogger(RedPacketsApi.class);

    //发红包
    @RequestMapping(value="/distributeRedPackets")
    public ResponseBean distributeRedPackets(HttpServletRequest request) throws Exception {
        String uid = request.getParameter("uid");
        if(uid == null || uid.equals(""))
            return ResponseBean.fail("缺少用户ID参数!");

        String vid = request.getParameter("vid");
        if(vid == null || vid.equals(""))
            return ResponseBean.fail("缺少视频ID参数!");

        String sum = request.getParameter("sum");
        if(sum == null || sum.equals(""))
            return ResponseBean.fail("缺少红包个数参数!");
        if(Integer.parseInt(sum) < 1)
            return ResponseBean.fail("缺少红包个数不能少于1!");

        String money = request.getParameter("money");
        if(money == null || money.equals(""))
            return ResponseBean.fail("缺少红包总金额参数!");
        if(Float.parseFloat(money) < 0)
            return ResponseBean.fail("红包总金额不能小于0!");

        String title = request.getParameter("title");

        Wallet wallet = walletService.selectBalanceByUid(Long.parseLong(uid));
        float balance = wallet != null? wallet.getBalance():0;
        if(balance < Float.parseFloat(money))
            return ResponseBean.fail("余额不足，请充值后再发红包!");

        RedPackets redPackets = new RedPackets();
        redPackets.setUid(Long.parseLong(uid));
        redPackets.setVid(Long.parseLong(vid));
        redPackets.setSum(Integer.parseInt(sum));
        redPackets.setMoney(Float.parseFloat(money));
        if(!(title == null || title.equals("")))
            redPackets.setTitle(title);
        redPackets.setRemain_sum(Float.parseFloat(money));
        redPackets.setRemain(Integer.parseInt(sum));
        redPackets.setRed_time((int)(new Date().getTime()/1000));

//        if(redPacketsService.insert(redPackets) < 1)
//            return ResponseBean.fail("数据库错误");
        redPacketsService.distributeRedPackets(redPackets, Float.parseFloat(money));

        logger.info("sum ： " + sum);
        logger.info("money ： " + money);
        //已用户id和视频id为key
        redisTemplate.opsForList().leftPushAll(uid + "_" + vid, RandomUtils.wxAlgorithm(Double.parseDouble(money), Integer.parseInt(sum)));

        return ResponseBean.ok();
    }

    //抢红包
    @RequestMapping(value="/grabRedPackets")
    public ResponseBean grabRedPackets(HttpServletRequest request) throws Exception {
        String uid = request.getParameter("uid");
        if(uid == null || uid.equals(""))
            return ResponseBean.fail("缺少用户ID参数!");

        String vid = request.getParameter("vid");
        if(vid == null || vid.equals(""))
            return ResponseBean.fail("缺少视频ID参数!");


        Video video = videoService.selectById(Long.parseLong(vid));
        if(video == null)
            return ResponseBean.fail("该视频不存在!");

        User user = userService.queryUserInfo(Long.parseLong(uid));
        if(user == null)
            return ResponseBean.fail("该改用户不存在!");

        long remain = redisTemplate.opsForList().size(uid + "_" + vid);
        if(remain < 1) {
            redisTemplate.delete(uid + "_" + vid);
            return ResponseBean.fail("红包已抢完!");
        }

        if(grabRedPacketsService.queryRedPacketsByUid(Long.parseLong(uid)) != null)
            return ResponseBean.fail("你已抢过红包!");

        GrabRedPackets grabRedPackets = new GrabRedPackets();
        grabRedPackets.setUid(Long.parseLong(uid));
        grabRedPackets.setVid(Long.parseLong(vid));
        grabRedPackets.setGrab_money(Float.parseFloat("1"));
        grabRedPackets.setGrab_time((int)(new Date().getTime()/1000));
        float money = Float.parseFloat(redisTemplate.opsForList().leftPop(uid + "_" + vid).toString());

        Message message = new Message();
        message.setUid(video.getUid());
        message.setVid(video.getId());
        message.setOid(user.getId());
        message.setName(user.getNickname());
        message.setContent(Constant.MESSAGE_CONTENT3);
        message.setType(Constant.MESSAGE_TYPE2);
        message.setAvatar(user.getAvatar());
        message.setImage_path(video.getImage_path());
        message.setMessage_time((int)(new Date().getTime()/1000));

        Message message1 = null;
        if(remain == 1){
            message1 = new Message();
            message.setUid(video.getUid());
            message1.setVid(video.getId());
            message1.setName(Constant.MESSAGE_NAME);
            message1.setContent(Constant.MESSAGE_CONTENT1);
            message1.setType(Constant.MESSAGE_TYPE1);
            message1.setAvatar(Constant.MESSAGE_avatar);
            message1.setImage_path(video.getImage_path());
            message1.setMessage_time((int)(new Date().getTime()/1000));
        }
        grabRedPacketsService.grabRedPackets(grabRedPackets, Long.parseLong(vid), money, message, message1);

        return ResponseBean.ok(money);
    }

    //红包详情
    @RequestMapping(value="/redPacketsDetail")
    public ResponseBean redPacketsDetail(HttpServletRequest request) throws Exception {
        String vid = request.getParameter("vid");
        if (vid == null || vid.equals(""))
            return ResponseBean.fail("缺少视频ID参数!");

        Video video = videoService.selectById(Long.parseLong(vid));
        if(video == null)
            return ResponseBean.fail("该视频不存在!");

        return ResponseBean.ok(redPacketsService.redPacketsDetail(Long.parseLong(vid)));
    }
}
